const mqtt = require('mqtt')
const host = 'i6134ef3.cn-shenzhen.emqx.cloud'
const port = '11911'
const clientId = `mqtt_${Math.random().toString(16).slice(3)}`

// connect options
const OPTIONS = {
  clientId,
  clean: true,
  connectTimeout: 4000,
  username: 'test',
  password: 'test',
  reconnectPeriod: 1000,
}
let connectUrl = `mqtt://${host}:${port}`
const topic = 'mqtt'
const serverSocket = mqtt.connect(connectUrl, OPTIONS)
//监听服务器开启
serverSocket.on('connect', () => {
  console.log('服务器已连接')
  serverSocket.subscribe([topic + '/test_server'], () => {
    console.log(`已订阅'${topic}'`)
  })
})

serverSocket.on('error', (err) => {
  console.log('error: ', err)
})

//监听客户端发送的数据
serverSocket.on('message', (topic, payload) => {
  writeAndDrain(payload)
})

serverSocket.sendData = function (data) {
  data = data || ''
  serverSocket.publish(topic + '/test_client', data, { qos: 2, retain: false }, (error) => {
    if (error) {
      console.error(error)
    }
  })
}

var SerialPort = require("serialport").SerialPort;
var serialPort = new SerialPort("/dev/ttySAC1", {
  baudrate: 115200
});

function writeAndDrain (data) {
  serialPort.write(data, function () {
    console.log("6Q写入串口数据", data);
    serialPort.drain((e) => {
      console.log("6Q写入结果", e);
    });
  });
}

serialPort.on( "data", function( data ) {
  console.log("6Q接收串口数据", data);
  serverSocket.sendData(data)
});